#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: get_tapd_case_dir.py
# Author: ChenChangSong
# Date: 2025-08-24

"""
功能描述: 获取TAPD用例目录
"""

import json
import os
import sys
from os.path import abspath, dirname, join
# 不再添加项目路径到环境
from comm.common_code import *
from ui_code.common_ui import get_project_root
from tapd_capture_api.capture_get_dir_jsp import capture_get_dir_jsp

def get_tapd_case_directories():
    """获取TAPD目录(已有用例的目录)"""
    # 目录路径和目录ID的字典：{'固定目录不要删除': '1148433040001003468', '固定目录不要删除-qwer子目录': '1148433040001003469', '未规划目录': '-1'}
    # dir_path_name_and_id_dict = capture_get_dir()
    try:
        dir_path_name_and_id_dict = capture_get_dir_jsp()
        if dir_path_name_and_id_dict is None:
            logger.error("capture_get_dir_jsp() 返回了 None，无法获取目录")
            log_to_ui_error("capture_get_dir_jsp() 返回了 None，无法获取目录")
            return None, None

        # 将dir_path_name_and_id_dict缓存到files\save_files
        try:
            # 保存文件的目录
            save_dir = get_project_root() / "files" / "save_files"
            save_dir.mkdir(parents=True, exist_ok=True)
            
            with open(save_dir / 'tapd_dir_path_name_and_id_dict.json', 'w', encoding='utf-8') as f:
                # 对dir_path_name_and_id_dict进行排序
                # sorted_dir_path_name_and_id_dict = __sort_dict_by_path(dir_path_name_and_id_dict)
                json.dump(dir_path_name_and_id_dict, f, ensure_ascii=False, indent=4)
                logger.info(f"目录路径和id的字典已保存到{save_dir / 'tapd_dir_path_name_and_id_dict.json'}")
                log_to_ui_info(f"目录路径和id的字典已保存到{save_dir / 'tapd_dir_path_name_and_id_dict.json'}")
        except Exception as save_error:
            logger.warning(f"保存缓存文件失败: {save_error}，但继续执行")
            log_to_ui_warning(f"保存缓存文件失败: {save_error}，但继续执行")
        logger.info(f"目录路径和id的字典为：{dir_path_name_and_id_dict}")
        return dir_path_name_and_id_dict
        
    except Exception as e:
        logger.error(f"获取目录时发生异常: {str(e)}")
        return None

def __sort_dict_by_path(input_dict):
    """
    按照路径层级关系对字典进行排序
    """
    tree = {}
    for key, value in input_dict.items():
        parts = key.split('-')
        node = tree
        for part in parts:
            if part not in node:
                node[part] = {}
            node = node[part]
        node['__value__'] = value
    
    # 深度优先遍历收集排序后的键值对
    result = []
    
    def dfs(node, path_parts):
        # 如果当前节点有值，添加到结果
        if '__value__' in node:
            key = '-'.join(path_parts)
            result.append((key, node['__value__']))
        
        # 递归处理所有子节点（按名称排序）
        for child_name in sorted(node.keys()):
            if child_name != '__value__':
                dfs(node[child_name], path_parts + [child_name])
    
    # 从根节点开始遍历
    dfs(tree, [])
    
    # 转换为有序字典
    return dict(result)
if __name__ == "__main__":
    get_tapd_case_directories()